package com.wantupai.mvp.framework.support.manager;


import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;


import com.wantupai.mvp.mvp.MvpPresenter;

import java.util.Map;


/**
 * @author zhangqing
 * 用于缓存activity中对应的Presenter
 */
public class ActivityScopeCache {
    private final Map<String, PresenterHolder> presenterMap = new ArrayMap<String, PresenterHolder>();

    private static final class PresenterHolder {
        private MvpPresenter<?> presenter;
        private Object viewState;
    }


    //清空缓存
    public void clear() {
        presenterMap.clear();
    }

    //添加缓存p
    public void putPresenter(String viewId, MvpPresenter<?> presenter) {
        if (viewId == null) {
            throw new NullPointerException("viewId不能为空!");
        }
        if (presenter == null) {
            throw new NullPointerException("presenter 不能为空!");
        }
        PresenterHolder holder = presenterMap.get(viewId);
        if (holder == null) {
            holder = new PresenterHolder();
            holder.presenter = presenter;
            presenterMap.put(viewId, holder);
        } else {
            holder.presenter = presenter;
        }

    }

    //得到P
    public <P> P getPresenter(String viewId) {
        PresenterHolder presenterHolder = presenterMap.get(viewId);
        return presenterHolder == null ? null : (P) presenterHolder.presenter;
    }

    public void remove(String viewId) {
        if (viewId == null) {
            throw new NullPointerException("viewId不能为空");
        }
        presenterMap.remove(viewId);
    }

    public <VS> VS getViewState(String viewId) {
        PresenterHolder holder = presenterMap.get(viewId);
        return holder == null ? null : ((VS) holder.viewState);
    }

    public void putViewState(@NonNull String viewId, @NonNull Object viewState) {
        if (viewId == null) {
            throw new NullPointerException("viewId不能为空");
        }
        if (viewState == null) {
            throw  new NullPointerException("viewState不能为空");
        }
        PresenterHolder holder = presenterMap.get(viewId);
        if (holder == null) {
            holder = new PresenterHolder();
            holder.viewState = viewState;
            presenterMap.put(viewId, holder);
        } else {
            holder.viewState = viewState;
        }
    }
}
